<template>
	<view>
		<x-popup v-model="show" height="70vh" @hide="close">
			<view class="flex flex-center grid-gap-4">
				<view class="flex-1 text-center p-4 h9 font-weight-600">请选择项目</view>
			</view>
			<view class="flex-1 bg flex flex-column grid-gap-4 p-4 overflow-y-auto">
				<view class="bg-white p-4 rounded-4" v-for="(item, index) in list" :key="index">
					<x-project-item :project="item">
						<template #action>
							<x-input-number v-model="item.num"></x-input-number>
						</template>
					</x-project-item>
				</view>
			</view>
			<view class="flex p-4 flex-center">
				<view class="flex-3 flex flex-column grid-gap-2">
					<view>
						<text class="text-placheolder h9"> 合计： </text>
						<x-money type="danger-light-3" weight="bold" size="8" :money="price_sum">
							<template #prefix>
								<text class="h10 text-danger-light-3">￥</text>
							</template>
						</x-money>
					</view>
					<text v-if="remaining_minutes > 0" class="text-placeholder h10">
						当前{{WebConfigStore.replaceIndustryPersonnelName('技师')}}最多可加钟{{ remaining_minutes }}分钟
					</text>
				</view>
				<button class="flex-1 btn-primary btn-round" @tap="submit()">提交</button>
			</view>
			<view class="pb-safe-area"></view>
		</x-popup>
		<x-pay v-model:show="payTypeShow" :orders-type="form.type" @confirm="payCallBack" :price="price_sum" />
	</view>
</template>

<script setup lang="ts">
import { ref, watchEffect, reactive, defineProps, computed, nextTick } from 'vue';
import { usePlatformStore,useWebConfigStore, useRefs } from "@/stores";
import { $message, $api } from '@/utils';
import { $ResponseCode, $EventName } from '@/utils/const/env';
import { usePay } from '@/utils/pay';
const PlatformStore = usePlatformStore();
const { PLATFORM } = useRefs(PlatformStore);
const WebConfigStore = useWebConfigStore();
const props = withDefaults(defineProps<{
	show: boolean
	remaining_minutes: number
	projects: any[]
	appointment_service_id: number | string
}>(), {
	show: false,
	remaining_minutes: 0,
	projects: [],
	appointment_service_id: 0,
});
const show = ref(props.show)
const payTypeShow = ref(false)
const form = reactive({
	type: 'overtime',
	pay_type: '',
	appointment_service_id: props.appointment_service_id,
	code: '',
	project: [],
})
const orders = ref({})
const list = ref(props.projects)
const emit = defineEmits(['update', 'update:show'])
const price_sum = computed(() => {
	let price = 0;
	for (let i = 0; i < list.value.length; i++) {
		const item = list.value[i];
		if (item.num > 0) {
			if (item.overtime_separate) {
				price += item.overtime_price * item.num;
			} else {
				price += item.price * item.num;
			}
		}
	}
	return price.toFixed(2);
})

const submit = () => {
	form.platform = PLATFORM.value.platform;
	let project = list.value;
	let array = [];
	for (let i = 0; i < project.length; i++) {
		if (project[i].num > 0) {
			array.push({ num: project[i].num, apps_id: project[i].apps_id })
		}
	}
	if (array.length <= 0) {
		$message.error('请选择项目');
		return;
	}
	form.project = array;
	payTypeShow.value = true;
}
const payCallBack = (pay_type: string) => {
	payTypeShow.value = false;
	
	if (pay_type) {
		form.pay_type = pay_type;
		// #ifdef MP-WEIXIN
		wx.login({
			success: (res: any) => {
				if (res.code) {
					form.code = res.code;
					nextTick(() => {
						if (orders.value.trade) {
							getPayInfo();
						} else {
							getOrdersInfo();
						}
					})
				}
			},
			fail: () => {
				uni.showModal({
					title: '提示',
					content: '微信授权失败',
					showCancel: false,
					success: (res) => {
						if (res.confirm) {
							$page.back();
						}
					}
				});
			}
		})
		// #endif
		// #ifndef MP-WEIXIN
		console.log('payCallBack:',JSON.stringify(orders.value));
		if (orders.value.trade) {
			getPayInfo();
		} else {
			getOrdersInfo();
		}
		// #endif
	}
}
const getPayInfo = () => {
	uni.showLoading({
		title: '获取订单中...',
		mask: true
	})
	$api.Orders.payByOrders({
		trade: orders.value.trade,
		platform: form.platform,
		pay_type: form.pay_type,
		code: form.code
	}).then((res: any) => {
		if (res.data.order && res.data.order.trade) {
			orders.value = res.data.order
		}
		pay(res);
	}).catch((err: any) => {
		$message.error(err.msg);
		if (err.data && err.data.trade) {
			orders.value = err.data
		} else {
			orders.value = {
				trade: '',
			};
		}
	}).finally(() => {
		uni.hideLoading();
	})
}
const getOrdersInfo = () => {
	uni.showLoading({
		title: '获取订单中...',
		mask: true
	})
	$api.Orders.create(form).then((res: any) => {
		console.log('-----------create----------',form)
		if (res.data.order && res.data.order.trade) {
			orders.value = res.data.order
		}
		if(res.msg=='支付成功'){
			$message.success(res.msg);
			orders.value =[];
		} 
		
		pay(res);
		
	}).catch((err: any) => {
		$message.error(err.msg);
		if (err.data && err.data.trade) {
			orders.value = err.data
		}
	}).finally(() => {
		uni.hideLoading();
	})
}
const pay = (res: any) => {
	
	console.log('------------pay------------',JSON.stringify(res));
	if (res.code === $ResponseCode.SUCCESS) {
		setTimeout(() => {
			uni.showLoading({
				title: '查询中...',
				mask: true
			});
			
			usePay(res.data).then(() => {
				uni.$emit($EventName.UPDATE_ORDER);
				emit('update');
				$api.User.userinfo(this, true);
				close();
			}).catch(err => {
				if (err && err.msg) {
					$message.error(err.msg);
				}
			}).finally(() => {
				uni.hideLoading();
			});
		}, 300)
	} else if (res.code === $ResponseCode.PAY_SUCCESS) {
		uni.$emit($EventName.UPDATE_ORDER);
		emit('update');
		$api.User.userinfo(this, true);
		close();
	}
}
const close = () => {
	emit('update:show', false);
}
watchEffect(() => {
	show.value = props.show;
	if (show.value) {
		list.value = props.projects;
	}
})
</script>
